package forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        test1(1,10_0000_0000);
//        System.out.println("-----------1------------");
        test2(1,10_0000_0000);
        System.out.println("-----------2------------");
        test3(1,10_0000_0000);
        System.out.println("-----------3------------");
        test4(1,10_0000_0000);
        System.out.println("-----------4------------");

    }

    private static void test1(int start,int end){
        long startTime = System.currentTimeMillis();
        ForkJoinCount forkJoinCount = new ForkJoinCount(start,end);
        Long compute = forkJoinCount.compute();
        long endTime = System.currentTimeMillis();
        System.out.println("Time:"+(endTime-startTime));
        System.out.println("result:"+compute);
    }

    private static void test2(int start,int end){
        long startTime = System.currentTimeMillis();
        long compute = 0 ;
        for(int i = start; i <= end; i++){
            compute+=i;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("Time:"+(endTime-startTime));
        System.out.println("result:"+compute);
    }

    //交给ForkJoinPool池处理
    private static void test3(int start,int end) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> forkJoinCount = new ForkJoinCount(start,end);
//        forkJoinPool.execute(forkJoinCount); 无结果
        //有结果
        ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinCount);
        long endTime = System.currentTimeMillis();
        System.out.println("Time:"+(endTime-startTime));
        System.out.println("result:"+submit.get());
    }

    private static void test4(int start,int end){
        long startTime = System.currentTimeMillis();
        long sum = 0 ;
        sum = LongStream.rangeClosed(start,end).parallel().reduce(0,Long::sum);
        long endTime = System.currentTimeMillis();
        System.out.println("Time:"+(endTime-startTime));
        System.out.println("result:"+sum);
    }
}
